let city = ''
$.ajax({
  url: "../city.json",
  data: { action: "jQueryAjax" },
  type: "GET",
  async: false,
  success: function (data) {
    city = data
  },
  //返回数据的格式
  dataType: "json"
})
const enterpriseVue = new Vue({
  el: '#app',
  data() {
    return {
      rules: {//表单验证
        Article_SerialNumber: [{ required: true, message: '请选择商品', trigger: 'change' }],
        Total_Quantity: [
          { required: true, message: '请输入全部商品数量', trigger: 'blur' },
          { type: 'number', message: '商品数量必须为数字值' }
        ],
        Starting_Quantity: [
          { required: true, message: '请输入最低一次购买数量', trigger: 'blur' },
          { type: 'number', message: '购买数量必须为数字值' }
        ],
        Unit_Quantity: [{ required: true, message: '请选择单位量', trigger: 'change' }],
        Amount: [
          { required: true, message: '请输入金额', trigger: 'blur' },
          { type: 'number', message: '金额必须为数字值' }
        ],
        Delivery_Time: [{ required: true, message: '请选择发货时间', trigger: 'change' },],
        Outstation_Formula: [{ required: true, message: '请选择是否公布', trigger: 'change' }],
        Contacts: [{ required: true, message: '请输入联系人', trigger: 'blur' },],
        Contacts_Phone: [
          { required: true, message: '请输入联系人电话', trigger: 'blur' },
          { type: 'number', message: '手机号必须为数字值' }
        ],
        Delivery_Time: [{ required: true, message: '请选择交易时间', trigger: 'change' },],
      },
      rules2: {
        group_purchasing_shipment: [{ required: true, message: '请选择装运方式', trigger: 'change' }],
        group_purchasing_transport: [{ required: true, message: '请选择运输方式', trigger: 'change' }],
        group_purchasing_payment: [{ required: true, message: '请选择交易方式', trigger: 'change' }],
        Trading_SerialNumber:[{ required: true, message: '请选择付款周期', trigger: 'change' }],
      },
      article_info: [],//该企业的全部商品信息
      unit: [],
      Paymentmethod: [//支付方式
      ],
      Shippingmethod: [//运输方式
      ],
      transportationmethod: [//装运方式
      ],
      Payoutcycle: [//付款周期
      ],
      ispublish: [//付款周期
        {
          name: '公布',
          value: '1'
        },
        {
          name: '不公布',
          value: '0'
        },
      ],
      value: '',
      Payway: "",
      AllPayWay: [],
      QualityInspection: [//质量检验
      ],
      QuantityInspection: [//数量检验
      ],
      Payment_cycle_details: [
        {
          PaymentCycleStage: "定金",
          PaymentCycleAmount: "40",
          PaymentCycleLastTime: "0",
          PaymentCycleType: "",
          fkzqxz: []
        },
        {
          PaymentCycleStage: "发货",
          PaymentCycleAmount: "30",
          PaymentCycleLastTime: "5",
          PaymentCycleType: "",
          fkzqxz: []
        },
        {
          PaymentCycleStage: "到货",
          PaymentCycleAmount: "20",
          PaymentCycleLastTime: "5",
          PaymentCycleType: "",
          fkzqxz: []
        },
        {
          PaymentCycleStage: "尾款",
          PaymentCycleAmount: "10",
          PaymentCycleLastTime: "5",
          PaymentCycleType: "",
          fkzqxz: []
        },
      ],
      isArr: [],
      arr1: [],
      arr2: [],
      arr3: [],
      arr4: [],
      article_infos: {},//选择的商品
      num: '', //选择的数量
      units: '',//选择的单位
      form: { //要提交的表单
        Group_Purchasing_SerialNumber: '', //主键
        Article_SerialNumber: "", //商品主键
        Total_Quantity: "", //总数
        Starting_Quantity: "", //起步量
        Unit_Quantity: "", //单位量
        Amount: "", //金额
        Article_Unit_SerialNumber: "", //商品单位
        Delivery_Time: "", //发货时间
        Transaction_Location: "", //发货地点
        Supplementary_Explanation: '', //补充约定
        Contacts: '', //联系人
        Contacts_Phone: '', //联系人电话
        Picture_URL: '', //商品图片
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        Outstation_Formula: "",
        Sell_Quantity: 0,
        Residue_Quantity: 0,
        Quality_Acceptance_SerialNumber: '', //质量验收方式
        Quantity_Acceptance_SerialNumber: '', //数量验收方式
        Group_Purchasing_Name: '', // 标题Group_Purchasing_Name
        Delivery_Method: '1', // 交收方式单选Delivery_Method
        Supplementary_Provisions: '', // 补充条款
        Guarantee_Method: '1', // 保证金
        Trading_SerialNumber: "", //0为全款1为按条件付款
        Children: {
          group_purchasing_paystages: [],
          group_purchasing_shipment: [], //支持的运输方式
          group_purchasing_transport: [], //支持的装运方式
          group_purchasing_payment: [] //支持的打款方式
        }
      },
      fkzqxz2:{
        jd:'',
        date:1,
      },
      addressDetail: "",
      // 整个省市县数据
      city,
      // 被选中的市数据
      cityList: [],
      // 被选中的县数据
      areaList: [],
      selectProvince: {},
      selectCity: {},
      selectArea: {},
      address: '',
      loading: false//节流
    }
  },
  mounted() {
    this.getShopData()
    this.getMasterdata()
  },
  methods: {
    getShopData() {// 获取该企业全部商品
      let _this = this;
      $.ajax({
        url: DomainName + '/getInquiryAction',
        type: 'POST',
        data: {
          Data: "article_info",
          token: $.cookie("token")
        },
        success: function (res) {
          console.log(res)
          _this.article_info = res
        }
      })
    },
    change(e) {//输入框选择哪个商品就出现该商品的图片跟价格
      this.article_infos = this.article_info.filter(item => {
        return item.Article_SerialNumber == e
      })[0]
      console.log(this.article_infos)
    },
    changePay(e) {
      console.log(e)
      this.Payway = e
    },
    rdc() {
      if (this.Payment_cycle_details.length > 2) {
        this.Payment_cycle_details.pop()
      }
    },
    add() {
      if (this.Payment_cycle_details.length < 4) {
        console.log(this.Payment_cycle_details)
        this.Payment_cycle_details.push({
          PaymentCycleStage: "",
          PaymentCycleAmount: "",
          PaymentCycleLastTime: "0",
          PaymentCycleType: "",
          fkzqxz: this.AllPayWay.filter(item=>!this.isArr.some(id=>id.id==item.Trading_Detail_SerialNumber&&id.index!=2))
        },)
      }
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var _this = this
          this.form.Residue_Quantity = this.form.Total_Quantity
          this.form.Transaction_Location = this.selectProvince.label + '/'
            + this.selectCity.label + '/'
            + this.selectArea.label + '/'
            + this.addressDetail
          this.form.Residue_Quantity = this.form.Total_Quantity
          let percentage = 0
          //遍历添加给form的子表
          if(_this.Payway == 'T00000000000002'){
            _this.form.Children.group_purchasing_paystages = []
						_this.Payment_cycle_details.forEach(item => {
               percentage+=Number(item.PaymentCycleAmount)
							_this.form.Children.group_purchasing_paystages.push({
								Group_Seek_Paystages_SerialNumber: "",
								Group_Seek_Purchase_SerialNumber: "",
								Trading_Detail_SerialNumber: item.PaymentCycleType,
								Trading_Amount: item.PaymentCycleAmount,
								Trading_Date: item.PaymentCycleLastTime,
								Trading_Explain: item.PaymentCycleStage
							})
						})
          }else{
            percentage = 100
            _this.form.Children.group_purchasing_paystages = [{
              Group_Paystages_SerialNumber: "",
              Group_Purchasing_SerialNumber: "",
              Trading_Detail_SerialNumber: _this.fkzqxz2.jd,
              Trading_Amount: 100,
              Trading_Date: _this.fkzqxz2.date,
              Trading_Explain:"全额支付"
            }]
          }
          if(percentage!=100){
            this.$message.error('额度累加不等于100%')
            return
          }
          //遍历添加给form的子表
          this.arr2 = this.form.Children.group_purchasing_shipment
          this.form.Children.group_purchasing_shipment = []
          this.arr2.forEach(item => {
            this.form.Children.group_purchasing_shipment.push(
              {//装运方式
                Group_Purchasing_Shipment_SerialNumber: "",
                Group_Purchasing_SerialNumber: "",
                Shipment_SerialNumber: item.Shipment_SerialNumber
              }
            )
          })
          //遍历添加给form的子表
          this.arr3 = this.form.Children.group_purchasing_transport
          this.form.Children.group_purchasing_transport = []
          this.arr3.forEach(item => {
            this.form.Children.group_purchasing_transport.push(
              {//运输方式
                Group_Purchasing_Transport_SerialNumber: "",
                Group_Purchasing_SerialNumber: "",
                Transport_SerialNumber: item.Transport_SerialNumber,
              }
            )
          })
          //遍历添加给form的子表
          this.arr4 = this.form.Children.group_purchasing_payment
          console.log(this.arr4)
          this.form.Children.group_purchasing_payment = []
          this.arr4.forEach(item => {
            this.form.Children.group_purchasing_payment.push(
              {//支付方式
                Group_Purchasing_Payment_SerialNumber: "",
                Group_Purchasing_SerialNumber: "",
                Payment_SerialNumber: item.Payment_SerialNumber,
              }
            )
          })
          this.form.Picture_URL = this.article_infos.Picture_URL
          console.log(this.form)
          if (this.form.Total_Quantity < this.form.Starting_Quantity) {
            this.$message.error('最低单位量不可以超过总量')
            return
          }
          //正则验证手机号
          var reg = /^1[3-9]\d{9}$/
          //判断手机号是否符合格式
          if (!reg.test(this.form.Contacts_Phone)) {
            this.$message.error('手机号格式有误')
            return
          }
          //表单验证
          if (this.form.Children.group_purchasing_shipment.length == 0) {
            this.$message.error('请选择装运方式')
            return
          }
          if (this.form.Children.group_purchasing_transport.length == 0) {
            this.$message.error('请选择运输方式')
            return
          }
          if (this.form.Children.group_purchasing_payment.length == 0) {
            this.$message.error('请选付款周期')
            return
          }
          //节流
          this.loading = true
          if (_this.loading) {
            $.ajax({
              url: DomainName + '/getAddAction',
              type: 'POST',
              data: {
                Data: JSON.stringify({ "group_purchasing": [_this.form] }),
                token: $.cookie("token")
              },
              success: function (res) {
                _this.loading = false
                console.log(res)
                if (res.Status == 'success') {
                  _this.$message('企业审核中,请等待')
                  window.history.go(-1);
                }
              }
            })
          }
        } else {
          return;
        }
      })
    },
    changeFktype(e, i, item) {
      if (item.PaymentCycleType == '') {
        this.isArr = this.isArr.filter(item => item.index != i)
      } else {
        this.isArr.push({
          id: e,
          index: i
        })
      }
    },
    getMasterdata() {
      let this_ = this
      $.ajax({//获取所有支付方式
        type: 'POST',
        data: {
          Data: 'payment_info',
        },
        url: DomainName + '/GoodsFileInquiry',
        success: function (Result) {
          console.log(Result)
          this_.Paymentmethod = Result
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      })
      $.ajax({//获取所有运输方式
        type: 'POST',
        data: {
          Data: 'shipment_info',
        },
        url: DomainName + '/GoodsFileInquiry',
        success: function (Result) {
          console.log(Result)
          this_.Shippingmethod = Result
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      })
      $.ajax({//获取所有装运方式
        type: 'POST',
        data: {
          Data: 'transport_info',
        },
        url: DomainName + '/GoodsFileInquiry',
        success: function (Result) {
          console.log(Result)
          this_.transportationmethod = Result
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      })
      $.ajax({//获取所有商品单位
        type: 'POST',
        data: {
          Data: 'article_unit',
          Primary_Key_Name: 'Type', //外键属性名
          Primary_Key: '1', //主键值
        },
        url: DomainName + '/GoodsInquiryKey',
        success: function (Result) {
          console.log(Result)
          this_.unit = Result
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      })
      $.ajax({//获取所有付款周期
        type: 'POST',
        data: {
          Data: 'trading_info',
        },
        url: DomainName + '/GoodsFileInquiry',
        success: function (Result) {
          console.log(Result)
          this_.Payoutcycle = Result
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      })
      $.ajax({//获取所有质量验收方式
        type: 'POST',
        data: {
          Data: 'quality_acceptance',
        },
        url: DomainName + '/GoodsFileInquiry',
        success: function (Result) {
          console.log(Result)
          this_.QualityInspection = Result
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      })
      $.ajax({//获取所有数量验收方式
        type: 'POST',
        data: {
          Data: 'quantity_acceptance',
        },
        url: DomainName + '/GoodsFileInquiry',
        success: function (Result) {
          console.log(Result)
          this_.QuantityInspection = Result
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      })
      $.ajax({//获取所有付款周期细则
        type: 'POST',
        data: {
          Data: 'trading_detail',
        },
        url: DomainName + '/GoodsFileInquiry',
        success: function (Result) {
          this_.Payment_cycle_details.forEach(item => {
            item.fkzqxz = Result
          })
          console.log(Result)
          this_.AllPayWay = Result
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      })
    },
    selectProvinceFun(event) {// 省份 市 县联动
      console.log(event)
      if (event) {
        this.cityList = event.children
      } else {
        this.cityList = []
      }
      this.areaList = []
    },
    selectCityFun(event) {
      console.log(event)
      if (event) {
        this.areaList = event.children
      } else {
        this.areaList = []
      }
    },
    selectAreaFun(event) {
      if (event) {
        console.log(event)
        this.isdisabled = false
      } else {
        this.isdisabled = true
      }
    },
    selectAddress(event) {
      if (event && event != '' && this.selectArea.label != undefined) {
        this.form.Supplier_Address = this.selectProvince.label + '/'
          + this.selectCity.label + '/'
          + this.selectArea.label + '/'
          + this.address
      }
    },
  }
})